package com.tp.interceptor;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.tp.base.BaseController;
import com.tp.base.BaseForm;
import com.tp.utils.Attr;
import com.tp.utils.HttpRequestDeviceUtils;
import com.tp.utils.WebUtils;

/**
 * 公共属性拦截器
 * 
 */
public class CommonInterceptor implements Interceptor {

	public void intercept(Invocation ai) {
		Controller controller = ai.getController();
		// 设置公共属性
		if (controller instanceof BaseController) {
			BaseForm form = ((BaseController) controller).getModelByForm(BaseForm.class);
			controller.setAttr("form", form);
		}
		// 判断是否是移动端
		HttpServletRequest request = controller.getRequest();
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(Attr.SESSION_IS_MOILE);
		if (obj == null) {
			boolean isMoile = HttpRequestDeviceUtils.isMobileDevice(request);
			session.setAttribute(Attr.SESSION_IS_MOILE, isMoile);
		}
		// 如果没有，就设置一个
		Object key = controller.getSessionAttr(WebUtils.USER_KEY);
		if (key == null) {
			controller.setSessionAttr(WebUtils.USER_KEY, UUID.randomUUID().toString());
		}
		ai.invoke();
	}
}
